// 优惠券服务 - 用于获取优惠券管理页面的真实数据

export interface CouponData {
  id: string
  name: string
  type: string
  discount: string
  validPeriod: string
  applicableSites: string
  status: string
  createTime: string
  updateTime: string
}

// 从优惠券管理页面获取的真实数据结构
export interface CouponForm {
  id: string
  name: string
  description: string
  type: string
  amount: number
  minAmount: number
  discountRate?: number
  maxDiscount?: number
  validType: string
  startTime?: string
  endTime?: string
  validDays?: number
  validMinutes?: number
  logistics?: string
  status: string
  usageDesc: string
  quantityType: string
  quantity: number
  grantType: string
  customerTags: string
  selectedTags: string[]
  userIds: string
  sites: string[]
  scope: string[]
  validDesc?: string
  selectedCategories?: (string | number)[]
  selectedBrands?: (string | number)[]
  showInCouponCenter?: boolean
  couponCenterSort?: number
  couponCenterStatus?: 'active' | 'inactive'
  createdAt: string
}

// 从优惠券管理页面获取真实数据
// 这里模拟从优惠券管理页面的 couponList 获取数据
export const getAvailableCoupons = (): Promise<CouponData[]> => {
  return new Promise((resolve) => {
    // 模拟API调用延迟
    setTimeout(() => {
      // 模拟从优惠券管理页面获取的真实数据
      const rawCoupons: CouponForm[] = [
        { 
          id: '1001', 
          name: '新用户满减券', 
          description: '新人专享', 
          type: '满减券', 
          amount: 20, 
          minAmount: 100, 
          validType: 'fixed', 
          startTime: '2024-06-01', 
          endTime: '2024-06-30', 
          validDesc: '2024-06-01~2024-06-30', 
          status: '发布', 
          usageDesc: '新用户专享', 
          quantityType: 'unlimited', 
          quantity: 0, 
          grantType: 'system', 
          customerTags: '', 
          selectedTags: [], 
          userIds: '', 
          sites: ['all'], 
          scope: ['all'], 
          selectedCategories: [], 
          selectedBrands: [], 
          showInCouponCenter: true, 
          couponCenterSort: 1, 
          couponCenterStatus: 'active', 
          createdAt: '2024-06-01 10:00:00' 
        },
        { 
          id: '1002', 
          name: '全场包邮券', 
          description: '全场包邮', 
          type: '包邮券', 
          amount: 0, 
          minAmount: 0, 
          validType: 'today', 
          validDays: 7, 
          validDesc: '领券当日生效7天', 
          logistics: 'ems', 
          status: '作废', 
          usageDesc: '', 
          quantityType: 'limited', 
          quantity: 100, 
          grantType: 'targeted', 
          customerTags: 'b_all', 
          selectedTags: [], 
          userIds: '', 
          sites: ['all'], 
          scope: ['all'], 
          selectedCategories: [], 
          selectedBrands: [], 
          showInCouponCenter: false, 
          couponCenterSort: 0, 
          couponCenterStatus: 'inactive', 
          createdAt: '2024-06-02 14:30:00' 
        },
        { 
          id: '1003', 
          name: '夏日折扣券', 
          description: '夏季特惠', 
          type: '折扣券', 
          amount: 0, 
          minAmount: 50, 
          discountRate: 8.8, 
          maxDiscount: 30, 
          validType: 'timed', 
          validMinutes: 120, 
          validDesc: '领取后120分钟', 
          status: '发布', 
          usageDesc: '', 
          quantityType: 'unlimited', 
          quantity: 0, 
          grantType: 'system', 
          customerTags: '', 
          selectedTags: [], 
          userIds: '', 
          sites: ['mairo', 'yahoo_auction'], 
          scope: ['category'], 
          selectedCategories: [1, 11], 
          selectedBrands: [], 
          showInCouponCenter: true, 
          couponCenterSort: 3, 
          couponCenterStatus: 'active', 
          createdAt: '2024-06-03 09:15:00' 
        },
        { 
          id: '1004', 
          name: '无门槛券', 
          description: '无门槛减', 
          type: '无门槛券', 
          amount: 10, 
          minAmount: 0, 
          validType: 'tomorrow', 
          validDays: 3, 
          validDesc: '次日生效3天', 
          status: '草稿', 
          usageDesc: '', 
          quantityType: 'limited', 
          quantity: 50, 
          grantType: 'targeted', 
          customerTags: 'users', 
          selectedTags: [], 
          userIds: 'user001\nuser002\nuser003', 
          sites: ['all'], 
          scope: ['brand'], 
          selectedCategories: [], 
          selectedBrands: [1, 2], 
          showInCouponCenter: false, 
          couponCenterSort: 0, 
          couponCenterStatus: 'inactive', 
          createdAt: '2024-06-04 16:45:00' 
        }
      ]

      // 转换为领券中心需要的格式
      const coupons: CouponData[] = rawCoupons
        .filter(coupon => coupon.status === '发布') // 只获取已发布的优惠券
        .map(coupon => {
          // 根据优惠券类型生成优惠内容描述
          let discount = ''
          if (coupon.type === '满减券') {
            discount = `满${coupon.minAmount}减${coupon.amount}`
          } else if (coupon.type === '折扣券') {
            discount = `满${coupon.minAmount}享${coupon.discountRate}折`
            if (coupon.maxDiscount) {
              discount += `，最高减${coupon.maxDiscount}`
            }
          } else if (coupon.type === '包邮券') {
            discount = `免运费(${getLogisticsName(coupon.logistics || 'ems')})`
          } else if (coupon.type === '无门槛券') {
            discount = `无门槛减${coupon.amount}`
          }

          // 获取适用站点描述
          const applicableSites = getSitesDescription(coupon.sites)

          return {
            id: coupon.id,
            name: coupon.name,
            type: coupon.type,
            discount,
            validPeriod: coupon.validDesc || '',
            applicableSites,
            status: coupon.status,
            createTime: coupon.createdAt,
            updateTime: coupon.createdAt
          }
        })

      resolve(coupons)
    }, 300) // 模拟网络延迟
  })
}

// 获取物流方式名称
function getLogisticsName(logistics: string): string {
  const logisticsMap: Record<string, string> = {
    'ems': '日本邮政EMS',
    'sal': 'DHL',
    'air': '航空',
    'sea': '海运'
  }
  return logisticsMap[logistics] || logistics
}

// 获取适用站点描述
function getSitesDescription(sites: string[]): string {
  if (sites.includes('all')) {
    return '全站通用'
  }
  
  const siteMap: Record<string, string> = {
    'mairo': '煤炉',
    'yahoo_auction': '雅虎日拍',
    'yahoo_fleamarket': '雅虎闲置',
    'bookoff': 'bookoff'
  }
  
  return sites.map(site => siteMap[site] || site).join('、')
}

// 根据ID获取优惠券详情
export const getCouponById = (id: string): Promise<CouponData | null> => {
    return getAvailableCoupons().then(coupons => {
        return coupons.find(coupon => coupon.id === id) || null
    })
}

// 搜索优惠券
export const searchCoupons = (keyword: string): Promise<CouponData[]> => {
    return getAvailableCoupons().then(coupons => {
        if (!keyword) return coupons
        return coupons.filter(coupon =>
            coupon.name.includes(keyword) ||
            coupon.type.includes(keyword) ||
            coupon.discount.includes(keyword)
        )
    })
}

// 获取优惠券类型统计
export const getCouponTypeStats = (): Promise<Record<string, number>> => {
    return getAvailableCoupons().then(coupons => {
        const stats: Record<string, number> = {}
        coupons.forEach(coupon => {
            stats[coupon.type] = (stats[coupon.type] || 0) + 1
        })
        return stats
    })
}
